package cn.maihe.elg.operation.centers.quanzhou.channel;

import cn.maihe.elg.operation.centers.quanzhou.auth.QuanzhouCenterAuthConfig;
import cn.maihe.elg.operation.centers.quanzhou.config.QuanzhouInfoConfig;
import cn.maihe.elg.operation.centers.quanzhou.dto.QuanzhouBaseReqDTO;
import cn.maihe.elg.operation.centers.quanzhou.dto.QuanzhouBaseRespDTO;
import cn.maihe.elg.operation.centers.quanzhou.enums.QuanzhouRespCodeEnum;
import cn.maihe.elg.operation.centers.quanzhou.exception.QuanzhouException;
import cn.maihe.elg.operation.model.enums.CenterNoEnum;
import cn.maihe.elg.operation.utils.SM3Util;
import cn.maihe.elg.operation.utils.SM4Util;
import com.alibaba.fastjson.JSON;
import com.google.common.base.CharMatcher;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 泉州中心基础接口服务
 * @Author xxx
 * @Date 2025/08/31
 */
@Slf4j
@Service
public class


BaseQuanzhouCenterInterfaceService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private QuanzhouInfoConfig quanzhouInfoConfig;

    /**
     * 执行请求
     */
    public <T extends QuanzhouBaseRespDTO> T doRequest(String url, QuanzhouBaseReqDTO reqDTO, Class<T> responseClass) {
        try {
            // 获取配置信息
            QuanzhouCenterAuthConfig authConfig = quanzhouInfoConfig.getAuthConfig(CenterNoEnum.EPOINT_QUANZHOU);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 构建请求参数
            Map<String, Object> requestMap = buildRequestParams(reqDTO, authConfig);

            // 加密敏感字段
            encryptSensitiveFields(requestMap, authConfig);

            // 生成签名
            String signature = Arrays.toString(generateSignature(requestMap, authConfig));
            requestMap.put("sign", signature);

            String requestBody = JSON.toJSONString(requestMap);
            log.info("泉州中心请求URL: {}, 请求参数: {}", url, requestBody);

            HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

            log.info("泉州中心响应: {}", response.getBody());

            // 解析响应
            T respDTO = JSON.parseObject(response.getBody(), responseClass);

            // 验证响应
            validateResponse(respDTO);

            return respDTO;

        } catch (Exception e) {
            log.error("泉州中心请求异常: {}", e.getMessage(), e);
            throw new QuanzhouException(QuanzhouRespCodeEnum.SYSTEM_ERROR, "请求异常: " + e.getMessage());
        }
    }

    /**
     * 构建请求参数
     */
    private Map<String, Object> buildRequestParams(QuanzhouBaseReqDTO reqDTO, QuanzhouCenterAuthConfig authConfig) {
        Map<String, Object> params = new HashMap<>();

        // 添加认证信息
        params.put("appkey", authConfig.getQuanzhouAuthorization().getAppkey());
        params.put("platformcode", authConfig.getQuanzhouAuthorization().getPlatformcode());
        params.put("productcode", authConfig.getQuanzhouAuthorization().getProductcode());

        // 添加业务参数
        String jsonStr = JSON.toJSONString(reqDTO);
        Map<String, Object> reqMap = JSON.parseObject(jsonStr, Map.class);
        params.putAll(reqMap);

        return params;
    }

    /**
     * 加密敏感字段
     */
    private void encryptSensitiveFields(Map<String, Object> params, QuanzhouCenterAuthConfig authConfig) {
        String sm4Key = authConfig.getQuanzhouEncryption().getSm4Key();
        String sm4Iv = authConfig.getQuanzhouEncryption().getSm4Iv();

        // 需要加密的字段列表
        String[] encryptFields = {
                "cprojecttype", "cprojectname", "cprojectno", "cbidid", "cbidname",
                "cownerunit", "cownerunitcode", "fbidtime", "endtime", "reckonprice",
                "citycode", "tbyxq", "tendernoticeurl", "claimreason"
        };

               // 遍历需要加密的字段列表，对每个字段的值进行SM4加密处理
        for (String field : encryptFields) {
            Object value = params.get(field);
            // 检查字段值是否存在且不为空
            if (value != null && StringUtils.hasText(value.toString())) {
                try {
                    // 使用SM4算法对字段值进行加密
                    String encryptedValue = Arrays.toString(SM4Util.encrypt_ECB_Padding(value.toString().getBytes(), sm4Key.getBytes()));
                    params.put(field, encryptedValue);
                } catch (Exception e) {
                    log.error("字段{}加密失败: {}", field, e.getMessage());
                    throw new QuanzhouException(QuanzhouRespCodeEnum.ENCRYPT_ERROR, "字段加密失败");
                }

            }
        }
    }

    /**
     * 生成签名
     */
    private byte[] generateSignature(Map<String, Object> params, QuanzhouCenterAuthConfig authConfig) {
        try {
            // 构建签名字符串
            StringBuilder signStr = new StringBuilder();
            params.entrySet().stream()
                    .filter(entry -> !"sign".equals(entry.getKey()) && entry.getValue() != null)
                    .sorted(Map.Entry.comparingByKey())
                    .forEach(entry -> {
                        if (signStr.length() > 0) {
                            signStr.append("&");
                        }
                        signStr.append(entry.getKey()).append("=").append(entry.getValue());
                    });

            // 添加密钥
            signStr.append("&key=").append(authConfig.getQuanzhouAuthorization().getAppsecret());

            log.debug("签名原文: {}", signStr.toString());

            // 使用SM3算法对签名字符串进行摘要计算
            // 将signStr转换为UTF-8编码的字节数组，然后通过SM3Util工具类生成摘要
            return SM3Util.hash(signStr.toString().getBytes(StandardCharsets.UTF_8));


        } catch (Exception e) {
            log.error("生成签名失败: {}", e.getMessage());
            throw new QuanzhouException(QuanzhouRespCodeEnum.SIGN_ERROR, "生成签名失败");
        }
    }

    /**
     * 验证响应
     */
    private void validateResponse(QuanzhouBaseRespDTO respDTO) {
        if (respDTO == null) {
            throw new QuanzhouException(QuanzhouRespCodeEnum.SYSTEM_ERROR, "响应为空");
        }

        // 校验响应结果，如果返回码不为"1"表示业务处理失败，抛出业务异常
        if (!"1".equals(respDTO.getCode())) {
            throw new QuanzhouException(QuanzhouRespCodeEnum.SYSTEM_ERROR, respDTO.getMessage());
        }

    }

    public Iterable<? extends Publisher<?>> toString(CharMatcher any, CharMatcher any1, CharMatcher any2) {
        return null;
    }
}